import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useUserStore } from '@/stores/modules/user.js'

export const useThemeStore = defineStore(
  'theme',
  () => {
    const themeColor = ref('#409eff')
    //hex颜色转rgb颜色
    const hexToRgb = (color) => {
      color = color.replace('#', '')
      var hxs = color.match(/../g)
      for (var i = 0; i < 3; i++) {
        hxs[i] = parseInt(hxs[i], 16)
      }
      return hxs
    }
    //rgb颜色转hex颜色
    const rgbToHex = (r, g, b) => {
      var hexs = [r.toString(16), g.toString(16), b.toString(16)]
      for (var i = 0; i < 3; i++) {
        if (hexs[i].length == 1) hexs[i] = '0' + hexs[i]
      }
      return '#' + hexs.join('')
    }
    //颜色加深
    const darken = (color, level) => {
      var rgbc = hexToRgb(color)
      for (var i = 0; i < 3; i++) rgbc[i] = Math.floor(rgbc[i] * (1 - level))
      return rgbToHex(rgbc[0], rgbc[1], rgbc[2])
    }
    //颜色变淡
    const lighten = (color, level) => {
      var rgbc = hexToRgb(color)
      for (var i = 0; i < 3; i++) rgbc[i] = Math.floor((255 - rgbc[i]) * level + rgbc[i])
      return rgbToHex(rgbc[0], rgbc[1], rgbc[2])
    }
    //获取所有变淡的颜色
    const themeColorLighten = computed(() => {
      const colors = []
      for (let i = 1; i <= 9; i++) {
        colors.push(lighten(themeColor.value, i / 10))
      }
      return colors
    })
    //获取所有加深的颜色
    const themeColorDarken = computed(() => {
      const colors = []
      for (let i = 1; i <= 9; i++) {
        colors.push(darken(themeColor.value, i / 10))
      }
      return colors
    })
    //设置主题色
    const setThemeColor = (color) => {
      themeColor.value = color
      document.documentElement.style.setProperty('--el-color-primary', color)
      //生成 --el-color-primary-light 颜色
      for (let i = 1; i <= 9; i++) {
        document.documentElement.style.setProperty(`--el-color-primary-light-${i}`, `${lighten(color, i / 10)}`)
      }
      //生成 --el-color-primary-dark 颜色
      for (let i = 1; i <= 9; i++) {
        document.documentElement.style.setProperty(`--el-color-primary-dark-${i}`, `${darken(color, i / 10)}`)
      }
      const userStore = useUserStore()
      localStorage.setItem(userStore.userInfor.cardNumber + '_themeColor', color)
    }
    return {
      themeColor,
      themeColorLighten,
      themeColorDarken,
      setThemeColor
    }
  },
  {
    persist: true
  }
)
